<script setup>
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { loginApi, registerApi } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const router = useRouter()
const formRef = ref(null)

const status = ref('password') //'password'密码登录, 'code' 扫码登录 , 'register'注册, 'forget'忘记密码

//登录表单数据
const formData = ref({
  username: '',
  account: '',
  password: '',
  rePassword: '',
  isAgree: false,
})

//表单验证规则
const rules = ref({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 15, message: '账号长度在4到15个字符', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在2到10个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' },
  ],
  isAgree: [{ required: true, message: '请阅读并同意用户协议', trigger: 'change' }],
  rePassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

//清空表单
const clearForm = () => {
  formData.value = {
    username: '',
    account: '',
    password: '',
    rePassword: '',
    isAgree: false,
  }
}

//登录处理函数
const handleLogin = () => {
  //表单验证
  formRef.value.validate(async (valid) => {
    if (valid) {
      //协议
      if (!formData.value.isAgree) {
        ElMessage.error('请阅读并同意用户协议')
        return
      }

      //发送登录请求
      const res = await loginApi(formData.value)
      console.log('res:', res)
      if (res.data.code === 1) {
        ElMessage.success('登录成功')
      }
      //保存token
      localStorage.setItem('token', res.data.data.token)
      userStore.setUser(res.data.data)

      //跳转到主页
      router.push('/')
    } else {
      ElMessage.error('请检查输入项')
    }
  })
}

//处理状态变化函数
const handleStatus = (val) => {
  //切换成账号登录
  if (status.value == val) {
    status.value = 'password'
    return
  }
  status.value = val
  clearForm()
}

//更多选项处理函数
const handleCommand = (commend) => {
  clearForm()
  status.value = commend
}

//注册处理函数
const handleRegister = () => {
  //表单验证
  formRef.value.validate(async (valid) => {
    if (valid) {
      //发送注册请求
      const res = await registerApi(formData.value)
      if (res.data.code === 1) {
        ElMessage.success('注册成功')
        handleStatus('password')
      } else {
        ElMessage.error(res.data.msg)
      }
    }
  })
}
</script>

<template>
  <div class="login-box" :style="{ height: status === 'register' ? '560px' : '500px' }">
    <!--头部-->
    <div class="header">
      <div class="title">欢迎使用QQ聊天系统</div>
      <div class="logo"><img src="@/assets/logo.png" /></div>
    </div>
    <!--主体部分）-->
    <div class="main">
      <!--登录-->
      <el-form
        v-if="status === 'password'"
        class="login-form"
        :model="formData"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="账号:" prop="account">
          <el-input type="primary" placeholder="请输入账号" v-model="formData.account"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input type="primary" placeholder="请输入密码" v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item class="center-item">
          <!--协议确认框-->
          <el-checkbox v-model="formData.isAgree">
            <span>我已阅读并同意<a href="#">《用户协议》</a></span>
          </el-checkbox>
        </el-form-item>
        <el-form-item class="center-item">
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>

      <!--注册--->
      <el-form
        v-if="status === 'register'"
        class="login-form"
        :model="formData"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="昵称:" prop="username">
          <el-input
            type="primary"
            placeholder="请输入注册的昵称"
            v-model="formData.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input type="primary" placeholder="请输入密码" v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item label="确认:" prop="rePassword">
          <el-input
            type="primary"
            placeholder="请确认密码"
            v-model="formData.rePassword"
          ></el-input>
        </el-form-item>
        <el-form-item class="center-item">
          <!--协议确认框-->
          <el-checkbox v-model="formData.isAgree">
            <span>我已阅读并同意<a href="#">《用户协议》</a></span>
          </el-checkbox>
        </el-form-item>
        <el-form-item class="center-item">
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>

      <!--忘记密码-->
      <el-form v-if="status === 'forget'" class="login-form"> </el-form>

      <!--扫码登录-->
      <div class="code" v-if="status === 'code'">
        <div class="qrcode"><img src="@/assets/qrcode.png" /></div>
        <div class="tip">请使用手机QQ扫描登录</div>
      </div>
    </div>
    <!--底部-->
    <div class="buttom">
      <div class="codeLogin">
        <el-link @click="handleStatus('code')" href="#/login" :underline="false">{{
          status === 'code' ? '账号登录' : '扫码登录'
        }}</el-link>
      </div>
      <div class="more">
        <el-dropdown placement="top" @command="handleCommand">
          <el-link href="#/login" :underline="false">更多选项</el-link>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="password" v-if="status !== 'password'"
                >返回登录</el-dropdown-item
              >
              <el-dropdown-item command="register">注册账号</el-dropdown-item>
              <el-dropdown-item command="forget">忘记密码</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
//给全局设置背景颜色:渐变色
body {
  background: linear-gradient(135deg, #f5f7fa 0%, #ebf0f5 100%);
}
a {
  //去除超链接下划线
  text-decoration: none;
  color: skyblue;
}

.login-box {
  width: 400px;
  height: 500px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border: solid 1px #ccc;
  margin-top: 100px;
  .header {
    text-align: center;
    .title {
      margin-bottom: 20px;
      font-size: 24px;
      color: #333;
      margin-top: 20px;
    }
    .logo {
      img {
        border-radius: 50%;
        width: 100px;
        height: 100px;
      }
    }
  }

  .main {
    .code {
      div {
        margin-top: 20px;
      }
      .tip {
        margin-bottom: 30px;
        font-weight: 700;
      }
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      .qrcode {
        img {
          width: 200px;
          height: 200px;
        }
      }
    }
    .login-form {
      .el-form-item {
        margin-top: 30px;
      }
      input {
        height: 40px;
      }
      //居中
      .center-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        button {
          width: 250px;
          height: 40px;
        }
      }
    }
  }

  .buttom {
    div {
      margin-left: 20px;
    }
    display: flex;
    justify-content: center;

    .codeLogin {
      margin-right: 20px;
    }
    .more {
      display: flex;
      align-items: center;
      margin-top: 5px;
      .el-dropdown {
        margin-left: 20px;
      }
    }
  }
}
</style>
